package com.wsgxj.shiro;

import com.wsgxj.domain.sys.SysUser;
import com.wsgxj.service.sys.SysMenuService;
import com.wsgxj.service.sys.SysRoleService;
import com.wsgxj.service.sys.SysUserService;
import com.wsgxj.util.ShiroUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm{

	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private SysRoleService sysRoleService;

	//认证
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		//用户输入的用户名和密码
		String username = (String) token.getPrincipal();
		String password = new String((char[])token.getCredentials());
		
		//查询数据库中的用户信息
		SysUser user = sysUserService.getByUsername(username);
		
		//账号不存在
		if(user == null) {
			throw new UnknownAccountException("账号不存在");
		}
		//密码验证可不在此处处理，利用shiroSimpleAuthenticationInfo与token进行验证，会抛出异常，一般不用
		//密码不正确
		if(!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException("密码不正确");
		}
		//用户被锁定
		if(user.getStatus() == 0) {
			throw new LockedAccountException("账号已被锁定，请联系管理员");
		}
		
		//加盐
//		ByteSource byteSalt = ByteSource.Util.bytes(user.getUsername());
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		//获取用户id,放到session
		ShiroUtil.setSessionAttribute("id",user.getUserId());
		//获取用户角色信息，放入session
		List<String> roleList = sysRoleService.selectRoleNameList(user.getUserId());
		ShiroUtil.setSessionAttribute("roles", roleList);
		
		return info;
	}
	
	//授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//System.out.println("授权");
		SysUser user = (SysUser) principals.getPrimaryPrincipal();
		//分配权限
		
		//用户角色列表
		List<String> roleList = sysUserService.findRoleListByUserId(user.getUserId());
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//分配角色权限
		info.addRoles(roleList);
		
		List<String> permissions = sysMenuService.getUserPermsList(user.getUserId());
		//此处可把permissions放入session中，用于控制器前台js生成的按钮或标签，也可用于检查权限越界
		ShiroUtil.getSession().setAttribute("shiroPermission", permissions);
		//for (String perm : permissions) {
		//	System.out.print(perm + ";");
		//}
        //System.out.println();
		//分配资源权限
		info.addStringPermissions(permissions);
		
		return info;
	}

}
